package servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = "/uploadtest")
public class uploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建上传文件的对象
        try {
            SmartUpload smartUpload = new SmartUpload();
            //2.初始化上传操作
            //2.1 获得初始的getPageContext值
            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this, req, resp, null, false, 1024, true);
            smartUpload.initialize(pageContext);
            //2.2 设置编码
            smartUpload.setCharset("utf-8");
            //3.上传
            smartUpload.upload();
            //4.获取文件信息
            File file = smartUpload.getFiles().getFile(0); // 获得单个文件
            String uname = smartUpload.getRequest().getParameter("uname");
            //4.1获得文件的文件名
            String fieldName = file.getFieldName();
            //4.2获得文件的类型
            String contentType = file.getContentType();
            //5.指定上传路径
            String filepath ="/filespath/"+fieldName;
            //6.保存到上传路径3
            file.saveAs(filepath,File.SAVEAS_VIRTUAL);
            //7.跳转到成功页面
                //7.1 跳转成功之前，需要把文件名存一下，方便在前端页面输出
            req.setAttribute("filesname",fieldName);
            req.setAttribute("uname",uname);
                //7.2 跳转到成功页面
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}
